import json
import asyncio
import threading
from redis import Redis
from app.api.websockets.manager import manager
from app.core.config import settings

class WebSocketSubscriber:
    def __init__(self):
        self.redis = Redis(
            host=settings.REDIS_HOST,
            port=settings.REDIS_PORT,
            password=settings.REDIS_PASSWORD,
            decode_responses=True
        )
        self.pubsub = self.redis.pubsub()
        self.channel = "websocket_messages"
        self.running = False
        self.thread = None
    
    def start(self):
        """启动订阅线程"""
        if not self.running:
            self.running = True
            self.pubsub.subscribe(self.channel)
            self.thread = threading.Thread(target=self._listen)
            self.thread.daemon = True
            self.thread.start()
    
    def _listen(self):
        """监听Redis通道并处理消息"""
        for message in self.pubsub.listen():
            if not self.running:
                break
                
            if message['type'] == 'message':
                try:
                    data = json.loads(message['data'])
                    client_id = data.get('client_id')
                    if client_id:
                        # 创建一个新的事件循环来处理异步发送
                        loop = asyncio.new_event_loop()
                        asyncio.set_event_loop(loop)
                        try:
                            # 构建WebSocket消息
                            ws_message = {
                                "task_id": data.get("task_id"),
                                "type": data.get("type"),
                                "data": data.get("data")
                            }
                            # 异步发送消息
                            loop.run_until_complete(manager.send_personal_message(ws_message, client_id))
                        finally:
                            loop.close()
                except Exception as e:
                    print(f"处理WebSocket消息时出错: {str(e)}")
    
    def stop(self):
        """停止订阅"""
        self.running = False
        self.pubsub.unsubscribe()
        if self.thread:
            self.thread.join(timeout=1.0)

# 创建全局实例
websocket_subscriber = WebSocketSubscriber()